// // 路由权限文件
// // 利用导航守卫实现
import router from './router'
import store from './store'

// 全局前置路由守卫
router.beforeEach(async(to, from, next) => {
  const token = store.state.user.token
  if (token) {
    if (to.path === '/login') {
      next('/')
    } else {
      // 必须有token和用户信息才能让你访问
      if (!store.state.user.userInfo.id) {
        await store.dispatch('user/getUserInfo')
        await store.dispatch('user/getUserQuanXian')
        const menus = store.state.user.quanxian.menus // 菜单权限
        console.log(menus)
        const routes = await store.dispatch('permissios/filterRoutes', menus)
        router.addRoutes([...routes, { path: '*', redirect: '/404', hidden: true }]) // 把筛选出来的路由追加到路由数组中
        return next(to.path)
      }
      next()
    }
  } else {
    const writer = ['/login', '/404', '/zhuce']
    if (writer.indexOf(to.path) !== -1) {
      next()
    } else {
      next('/login')
    }
  }
})
